//
//  CLPlayer.swift
//  clreader
//
//  Created by colin on 2019/4/8.
//  Copyright © 2019 colin. All rights reserved.
//

import AVKit

class CLPlayer: AVPlayer {

    let tlTimeControlStatus = Observable(AVPlayer.TimeControlStatus.waitingToPlayAtSpecifiedRate)
    let tlRate = Observable(CGFloat(0))
    
    override init() {
        super.init()
    }
    
    override init(playerItem item: AVPlayerItem?) {
        super.init(playerItem: item)
        self.addObserver(self, forKeyPath: "timeControlStatus", options: .new, context: nil)
        self.addObserver(self, forKeyPath: "rate", options: .new, context: nil)
    }
    
    deinit {
        self.removeObserver(self, forKeyPath: "timeControlStatus")
        self.removeObserver(self, forKeyPath: "rate")
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        guard let key = keyPath else { return }
        
        if key == "timeControlStatus" {
            self.tlTimeControlStatus.value = self.timeControlStatus
        } else if key == "rate" {
            self.tlRate.value = CGFloat(self.rate)
        }
    }
    
}
